<?php

    function get_session() {
        if( session_status() != PHP_SESSION_ACTIVE ) session_start();

        if( ! (isset($_SESSION['user_id']) && isset($_SESSION['session_id'])) ) {
            return false;
        } else {
            $model = new Usuario();
            return $model->validate_user_status( $_SESSION['user_id'], $_SESSION['session_id'] );
        }
    }

    function open_session( $id ) {
        if( session_status() != PHP_SESSION_ACTIVE ) session_start();

        $_SESSION['user_id']    = $id;
        $_SESSION['session_id'] = $_COOKIE['PHPSESSID'];
        $model = new Usuario();
        return $model->store_session( $id, $_SESSION['session_id'] );
    }

    function close_session() {
        if( session_status() != PHP_SESSION_ACTIVE ) session_start();

        $id = ( isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null );

        if( ! $id ) return false;
        else {
            session_unset();
            $model = new Usuario();
            if( ! $model->clear_session($id) ) return false;
            else                               return true;
        }
    }

    function add_product( $product ) {
        if( session_status() != PHP_SESSION_ACTIVE ) session_start();

        if( isset($_SESSION['productos']) ) {
            $arr = unserialize( $_SESSION['productos'] );
            if( ! in_array($product, $arr) ) array_push( $arr, $product );
            $_SESSION['productos'] = serialize( $arr );
        } else {
            $_SESSION['productos'] = serialize( array($product) );
        }
    }

    function clear_products() {
        if( session_status() != PHP_SESSION_ACTIVE ) session_start();

        if( isset($_SESSION['productos']) ) unset( $_SESSION['productos'] );
    }

?>